const express = require('express');
const fs = require('fs');
const path = require('path');
const moment = require('moment');
const cors = require('cors');
// npm install express moment cors --save
const app = express();
app.use(cors({
    origin: '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true,
    optionsSuccessStatus: 200
}));
app.use(express.json());
const DATE_FORMAT = `YYYY/MM/DD HH:mm:ss`;
const dataFilePath = path.resolve(__dirname, './data.json');
let tasks;
if (!fs.existsSync(dataFilePath)) {
    tasks = [];
    fs.writeFileSync(dataFilePath, JSON.stringify(tasks));
} else {
    tasks = JSON.parse(fs.readFileSync(dataFilePath, 'utf-8'));
}
app.post('/tasks', (req, res) => {
    const {
        description,
        expected_completion_time
    } = req.body;
    const lastTask = tasks[tasks.length-1];
    const id = lastTask?lastTask.id+1:1;
    const newTask = {
        id,
        description,
        status: 1,
        creation_time: moment().format(DATE_FORMAT),
        expected_completion_time,
        actual_completion_time: null
    };
    tasks.push(newTask);
    fs.writeFileSync(dataFilePath, JSON.stringify(tasks));
    res.status(201).send(newTask);
});
app.delete('/tasks/:id', (req, res) => {
    const {
        id
    } = req.params;
    tasks = tasks.filter(task => task.id !== parseInt(id));
    fs.writeFileSync(dataFilePath, JSON.stringify(tasks));
    res.status(204).send();
});
app.put('/tasks/:id', (req, res) => {
    const { id } = req.params;
    tasks = tasks.map(task => {
        if (task.id === parseInt(id)) {
            task.status = 2;
            task.actual_completion_time = moment().format(DATE_FORMAT);
        }
        return task;
    });
    fs.writeFileSync(dataFilePath, JSON.stringify(tasks));
    res.status(200).send();
});
app.get('/tasks', (req, res) => {
    const { status } = req.query;
    let filteredTasks = tasks;
    if (status) {
        filteredTasks = tasks.filter(task => task.status === parseInt(status));
    }
    res.status(200).send(filteredTasks);
});
const port = 7896;
app.listen(port, () => {
    console.log(`Server is up and running on port ${port}`);
});